import { defineComponent } from 'vue';
import { BasicForm, useForm } from '@/components/Form';
import { BasicModal, useModalInner } from '@/components/Modal';
import { useMessage } from '@/hooks/web/useMessage';
import { addStudyRoomApi, putStudyRoomApi } from '../service';

export default defineComponent({
  name: 'ActionModal',
  emits: ['register', 'reload'],
  setup(_, { emit }) {
    const {
      createMessage: { success },
    } = useMessage();

    const [registerModal, { changeLoading, changeOkLoading, closeModal, setModalProps }] =
      useModalInner(async ({ record, type = 'add' }) => {
        changeLoading(true);
        changeOkLoading(true);
        setModalProps({ title: `${type === 'add' ? '新增' : '编辑'}自习室` });
        if (type === 'edit') {
          console.log(record);
          await setFieldsValue(record || {});
        }
        changeLoading(false);
        changeOkLoading(false);
      });

    const [registerForm, { validate, setFieldsValue }] = useForm({
      labelWidth: 100,
      baseColProps: { span: 24 },
      schemas: [
        {
          field: 'RoomID',
          label: 'RoomID',
          show: false,
          component: 'Input',
        },
        {
          field: 'RoomName',
          label: '自习室名称',
          component: 'Input',
          required: true,
          rules: [{ max: 50, message: '名称不能超过50个字符' }],
          componentProps: { placeholder: '请输入自习室名称' },
        },
        {
          field: 'TotalSeats',
          label: '座位数量',
          component: 'InputNumber',
          required: true,
          componentProps: {
            min: 1,
            max: 50,
            class: 'w-full',
          },
        },
        {
          field: 'Status',
          label: '状态',
          component: 'Select',
          required: true,
          componentProps: {
            options: [
              { label: '开放', value: 'Open' },
              { label: '关闭', value: 'Closed' },
              { label: '维护', value: 'Maintenance' },
            ],
          },
        },
      ],
      showActionButtonGroup: false,
    });

    const handleSubmit = async () => {
      changeLoading(true);
      changeOkLoading(true);

      try {
        const values = await validate();
        if (!values.RoomID) {
          await addStudyRoomApi(values);
          success('新增成功');
        } else {
          await putStudyRoomApi(values);
          success('更新成功');
        }
        closeModal();
        emit('reload');
      } finally {
        changeLoading(false);
        changeOkLoading(false);
      }
    };

    return () => (
      <BasicModal
        width={600}
        minHeight={300}
        onRegister={registerModal}
        destroyOnClose
        onOk={handleSubmit}
      >
        <div class="px-4">
          <BasicForm onRegister={registerForm} />
        </div>
      </BasicModal>
    );
  },
});
